<template>
  <div class="basic-page file-page" @click="handleCloseMoreList">
    <div class="ces-search">
      <div>
        <el-button-group style="margin-right: 20px">
          <el-button v-permission="'create'" type="primary" @click="handleCreateDir"><i class="co-icon-chuangjianwenjianjia" style="font-size: 14px !important;" />创建文件夹</el-button>
          <el-button v-permission="'upload'" type="primary" icon="el-icon-upload2" @click="handleUpload">上传文件</el-button>
        </el-button-group>
        <el-button-group v-show="selectionArr.length>0">
          <el-button v-if="isDownload" v-permission="'download'" type="primary" plain icon="el-icon-download" @click="handleBatchDownLoad">下载</el-button>
          <el-button v-if="isDel" v-permission="'delete'" type="primary" plain icon="el-icon-delete" @click="handleBatchDel">删除</el-button>
          <el-button v-if="isDel" v-permission="'update'" type="primary" plain icon="el-icon-edit-outline" :disabled="selectionArr.length> 1" @click="handleEdit(selectionArr[0])">重命名</el-button>
          <el-button v-permission="'copy'" type="primary" plain icon="el-icon-copy-document" @click="handleBatchCopy">复制到</el-button>
          <el-button v-permission="'move'" type="primary" plain icon="el-icon-document-copy" @click="handleBatchMove">移动到</el-button>
          <el-button v-if="isAllUninitiated" v-permission="'start'" type="warning" plain icon="el-icon-document-copy" @click="handleStart">发起审核</el-button>
          <el-button v-if="isTrack" v-permission="'track'" type="warning" plain icon="el-icon-document-copy" @click="handleTrack">跟踪</el-button>
          <el-button v-if="isAllSign" v-permission="'assign'" type="warning" plain icon="el-icon-document-copy" @click="handleAssign">签收</el-button>
        </el-button-group>
      </div>
      <el-form ref="searchData" inline :model="searchData">
        <el-form-item v-for="item in searchForm" :key="item.prop" :label="item.label" :prop="item.prop">
          <!-- 输入框 -->
          <el-input v-if="item.type==='Input'" v-model="searchData[item.prop]" :placeholder="item.placeholder" suffix-icon="el-icon-search" @keyup.enter.native.stop="handleSearch" />
          <!-- 下拉框 -->
          <el-select v-if="item.type==='Select'" v-model="searchData[item.prop]" clearable>
            <el-option v-for="op in item.options" :key="op.value" :label="op.name" :value="op.value" />
          </el-select>
        </el-form-item>
        <i v-if="!isList" class="co-icon-liebiao" style="line-height: 36px" @click="isList = !isList; selectionArr=[]" />
        <i v-else class="co-icon-suolvetuqiehuan" style="line-height: 36px" @click="isList = !isList; selectionArr=[]" />
      </el-form>
    </div>
    <vxe-toolbar size="medium" :refresh="isList ? {query: getList}: false">
      <template v-slot:buttons>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item v-if="breadcrumb.length > 1" style="cursor: pointer" @click.native="goBackLink(breadcrumb[breadcrumb.length-2])">返回上一级</el-breadcrumb-item>
          <el-breadcrumb-item v-for="(item,index) in breadcrumb" :key="index" style="cursor: pointer" @click.native="goBackLink(item)">{{ item.fileDirName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </template>
      <template v-slot:tools />
    </vxe-toolbar>
    <vxe-table
      v-if="isList"
      ref="xTree"
      size="medium"
      row-id="id"
      border
      resizable
      auto-resize
      highlight-hover-row
      :data="tableData"
      :loading="listLoading"
      :max-height="tableHeight"
      :header-cell-style="{
        'background-color': '#d9ecfe',
        'color': '#333',
        'border-bottom': '1px #dbdbdb solid'
      }"
      :tree-config="{children: 'children', iconOpen: 'el-icon-caret-bottom', iconClose: 'el-icon-caret-right'}"
      @header-row-class-name="handleTableClass"
      @checkbox-change="handleSelectionChange"
      @checkbox-all="handleSelectionChange"
      @cell-click="handleOpenDir"
    >
      <template v-for="(item, index) in columns">
        <vxe-table-column v-if="!item.type" :key="index" v-bind.sync="item['config']" />
        <vxe-table-column v-else-if="item.type === 'file'" :key="index" v-bind.sync="item['config']">
          <template v-slot="{ row }">
            <div style="width: 100%" class="drag-btn" @contextmenu.prevent="handleMoreOptClick(row, ...arguments)">
              <template>
                <img :src="fiiterFileImg(row,'fileImgL')" style="vertical-align: middle; margin-right: 10px">
              </template>
              <span v-if="row.fileExtension !== null">{{ row[item.config.field] }}</span>
              <span v-else>{{ row.fileDirName }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column v-else-if="item.type === 'selection'" :key="index" type="checkbox" width="40" />
        <vxe-table-column v-else-if="item.type === 'time'" :key="index" v-bind.sync="item['config']">
          <template slot-scope="scope">
            {{ parseTime(scope.row, item.config.field) }}
          </template>
        </vxe-table-column>
        <vxe-table-column v-else-if="item.type === 'copy'" :key="index" v-bind.sync="item['config']">
          <template slot-scope="scope">
            {{ scope.row[item.config.field] }}
            <el-tooltip class="item" effect="dark" content="复制" placement="top">
              <i v-clipboard:copy="scope.row[item.config.field]" v-clipboard:success="clipboardSuccess" class="el-icon-copy-document" />
            </el-tooltip>
          </template>
        </vxe-table-column>
        <vxe-table-column v-else-if="item.type === 'filter'" :key="index" v-bind.sync="item['config']">
          <template v-slot="{ row }">
            <span :class="row[item.config.field] | filterClassColor(item.option)" :style="row[item.config.field] | filterColor(item.option)">
              {{ row[item.config.field] | filterType(item.option) }}
            </span>
          </template>
        </vxe-table-column>
        <vxe-table-column v-else :key="index" v-bind.sync="item['config']">
          <template slot-scope="scope">
            <expand-item :colum="item" :row="scope.row" :render="item.render" />
          </template>
        </vxe-table-column>
      </template>
    </vxe-table>
    <!--    缩略图展示效果-->
    <div v-else>
      <el-checkbox v-model="checkAll" :indeterminate="selectionArr.length>0 && selectionArr.length < tableData.length" @change="handleCheckAllChange">全选</el-checkbox>
      <ul class="card-list">
        <li v-for="(item,index) in tableData" :key="index" :class="selectionArr.findIndex((n) => { return item.id === n.id }) < 0 ? 'normal' : 'active'" @click.stop="handleOpenDirList(item)" @contextmenu.prevent="handleMoreOptClick(item, ...arguments)">
          <div class="card-content">
            <i class="el-icon-success" @click.stop.prevent="handleSelectionList(item)" />
            <img :src="fiiterFileImg(item,'fileImg')" alt="">
            <div class="card-txt">
              <el-tooltip :content="item.fileExtension !== null ? item.fileOriginalName : item.fileDirName" placement="bottom" effect="light">
                <span v-if="item.fileExtension !== null">{{ item.fileOriginalName }}</span>
                <span v-else>{{ item.fileDirName }}</span>
              </el-tooltip>
            </div>
            <div v-if="item.fileExtension !== null && (pageType === 'prjmgt' || pageType === 'new_processes' ||pageType === 'summary')">
              <el-tag v-if="item.wsStatus === null" effect="plain" type="info" size="mini">待发起</el-tag>
              <el-tag v-else-if="item.wsStatus === 'pending'" effect="plain" type="primary" size="mini">审批中</el-tag>
              <el-tag v-else-if="item.wsStatus === 'finished'" effect="plain" type="success" size="mini">审核通过</el-tag>
              <el-tag v-else-if="item.wsStatus === 'terminated'" effect="plain" type="danger" size="mini">已终止</el-tag>
              <el-tag v-else-if="item.wsStatus === 'rejected'" effect="plain" type="danger" size="mini">已驳回</el-tag>
              <el-tag v-else-if="item.wsStatus === 'sign'" effect="plain" type="warning" size="mini">待签收</el-tag>
              <el-tag v-else-if="item.wsStatus === 'delegate'" effect="plain" type="primary" size="mini">委派中</el-tag>
              <el-tag v-else-if="item.wsStatus === 'delegated'" effect="plain" type="primary" size="mini">委派任务完成</el-tag>
              <el-tag v-else-if="item.wsStatus === 'rollback'" effect="plain" type="primary" size="mini">已回退</el-tag>
              <el-tag v-else-if="item.wsStatus === 'delete'" effect="plain" type="primary" size="mini">流程已删除</el-tag>

            </div>
          </div>
        </li>
      </ul>
    </div>
    <!-- 右击快捷菜单-->
    <ul class="moreList" :style="styleObject">
      <li @click="handleOpenDirList(selectedRow)">打开</li>
      <li v-if="isDownload" v-permission="'download'" @click="handleBatchDownLoad">下载</li> <el-divider />
      <li v-permission="'copy'" @click="handleBatchCopy()">复制到</li>
      <li v-permission="'move'" @click="handleBatchMove()">移动到</li> <el-divider />
      <li v-if="selectedRow.fileExtension !== null" v-permission="'renew'" @click="handleRenew(selectedRow)">更新</li>
      <li v-if="isAllUninitiated" v-permission="'start'" @click="handleStart()">发起审核</li>
      <li v-if="isTrack" v-permission="'track'" @click="handleTrack">跟踪</li>
      <li v-if="isAllSign" v-permission="'assign'" @click="handleAssign()">签收</li><el-divider />
      <!--      只能是审核人才能进行审核且状态为审核中-->
      <!--      <li v-if="selectedRow.fileExtension !== null && selectedRow.wsStatus === 'pending'" @click="handlePreviewOrCheck(selectedRow,'check')">审核</li><el-divider />-->
      <!--      只有自己创建的并在审核中的可以撤销审核-->
      <!--      <li v-if="selectedRow.fileExtension !== null && selectedRow.wsStatus === 'pending' && selectedRow.createUsername === name" @click="handleBack(selectedRow)">撤销审核</li><el-divider />-->
      <li v-if="isDel" v-permission="'update'" @click="handleEdit(selectedRow)">重命名</li>
      <li v-if="isDel" v-permission="'delete'" @click="handleBatchDel">删除</li>
    </ul>
    <!--上传附件-->
    <el-dialog :close-on-click-modal="false" :title="isNewFile? '上传附件' : '更新附件'" :visible.sync="showUpload" width="400px">
      <div>
        <el-form v-if="isNewFile" ref="dataFormUpload" :rules="rulesUpload" :model="uploadData" label-position="right" label-width="90px" style="width: 100%;margin-bottom: 10px">
          <el-form-item label="附件类型" prop="fileType">
            <el-select v-model="uploadData.fileType" placeholder="请选择" :disabled="!(pageType === 'prjmgt' || pageType === 'outsource')">
              <el-option
                v-for="item in synTypeOptions"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-upload
          v-if="isNewFile"
          class="upload-demo"
          drag
          :action="uploadAction"
          :headers="uploadHeader"
          :data="uploadData"
          :limit="1"
          :before-upload="handleBeforeUpload"
          :on-success="handleSuccess"
          :on-exceed="handleExceed"
          accept="application/msexcel,application/msword,application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,video/*,image/*,.zip"
          :file-list="fileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-upload
          v-else
          class="upload-demo"
          drag
          :action="uploadAction"
          :headers="uploadHeader"
          :data="uploadRenewData"
          :limit="1"
          :on-success="handleSuccessRenew"
          :on-exceed="handleExceed"
          accept="application/msexcel,application/msword,application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,video/*,image/*,.zip"
          :file-list="fileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer" />
    </el-dialog>
    <!--复制或移动-->
    <el-dialog :close-on-click-modal="false" :title="dialogMoveStatus" :visible.sync="dialogMoveOrCopyVisible" width="500px">
      <el-input
        v-model="filterText"
        placeholder="输入文件名进行过滤"
      />
      <el-tree
        ref="tree"
        class="filter-tree"
        :data="DirTree"
        :props="defaultProps"
        highlight-current
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        node-key="id"
      >
        <span slot-scope="{ node }" class="custom-tree-node">
          <!--可以根据情况，以数据类型来显示不同的图标或图片-->
          <i :class="node.expanded ?'co-icon-zg-folder-opened-fill' : 'co-icon-folder_opened'" />
          <span>{{ node.label }}</span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogMoveOrCopyVisible = false">取 消</el-button>
        <el-button v-if="dialogMoveStatus === '复制到'" type="primary" @click="handleCopyOrMove('Copy')">确 定</el-button>
        <el-button v-else type="primary" @click="handleCopyOrMove('Move')">确 定</el-button>
      </span>
    </el-dialog>
    <!--发起审核-->
    <el-dialog :close-on-click-modal="false" title="发起审核" :visible.sync="dialogFormVisible" :modal-append-to-body="false" width="1200px">
      <el-steps :active="activeStep" finish-status="success" simple style="margin-top: 20px">
        <el-step title="第一步 选择流程" />
        <el-step title="第二步 选择处理人" />
        <el-step title="第三步 填写信息" />
      </el-steps>
      <el-card shadow="always" style="width: 70%;margin: 30px auto">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
          <el-form-item v-show="activeStep === 1" label="审核流程" prop="processDefinitionId">
            <el-select v-model="temp.processDefinitionId" placeholder="请选择" clearable @change="handleCandidate">
              <el-option
                v-for="item in workFlowOptions"
                :key="item.wbProcDefId"
                :label="item.workflowName"
                :value="item.wbProcDefId"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="activeStep === 2" label="审批人员" prop="candidate">
            <el-radio-group v-model="radio" @change="changeRadio">
              <el-radio v-if="candidateOptions.assignee" label="assignee">指定人员</el-radio>
              <el-radio v-if="candidateOptions.candidateUsers" label="candidateUsers">候选组</el-radio>
              <el-radio v-if="candidateOptions.candidateGroups" label="candidateGroups">角色人员</el-radio>
            </el-radio-group>
            <el-select v-if="radio === 'assignee'" v-model="temp.candidate" placeholder="请选择" class="filter-item" style="width: 100%" disabled>
              <el-option v-for="(item, index) in candidateOptions.assignee" :key="index" :label="item.nickname" :value="item.username" />
            </el-select>
            <el-select v-if="radio === 'candidateUsers'" v-model="temp.candidate" placeholder="请选择" clearable class="filter-item" filterable style="width: 100%">
              <el-option v-for="(item, index) in candidateOptions.candidateUsers" :key="index" :label="item.nickname" :value="item.username" />
            </el-select>
            <el-select v-if="radio === 'candidateGroups'" v-model="temp.candidate" placeholder="请选择" clearable class="filter-item" filterable style="width: 100%">
              <el-option-group v-for="(group, index) in candidateOptions.candidateGroups" :key="index" :label="group.groupName">
                <el-option v-for="item in group.userList" :key="item.username" :label="item.nickname" :value="item.username" />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item v-show="activeStep === 3" label="起止时间" prop="rangeTime">
            <el-date-picker v-model="temp.rangeTime" :picker-options="pickerOptions" type="datetimerange" :default-time="['08:30:00', '18:00:00']" style="width: 100%" clearable />
          </el-form-item>
          <el-form-item v-show="activeStep === 3" label="优先级" prop="priority">
            <el-select v-model="temp.priority" placeholder="请选择">
              <el-option
                v-for="item in priorityOptions"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="activeStep === 3" label="备注" prop="description">
            <el-input v-model="temp.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <div v-html="svgSrc" />

      </el-card>
      <div slot="footer" class="dialog-footer">
        <div v-if="activeStep === 1">
          <el-button type="primary" @click="changeStep('next','processDefinitionId')">
            下一步
          </el-button>
        </div>
        <div v-else-if="activeStep === 2">
          <el-button type="primary" @click="changeStep('pre')">
            上一步
          </el-button>
          <el-button type="primary" @click="changeStep('next','candidate')">
            下一步
          </el-button>
        </div>
        <div v-else>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="startData()">
            确定
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!--跟踪-->
    <el-dialog :close-on-click-modal="false" :visible.sync="trackDialogVisible" :modal-append-to-body="false" width="1200px">
      <div style="width: 1000px; margin: 0 auto" v-html="svgSrc" />
    </el-dialog>
  </div>
</template>

<script>
import clipboard from '@/directive/clipboard' // use clipboard by v-directive
import * as list from '@/api/getTableList'
import moment from 'moment'
import { dirCommand, findDirTree, fileCommand, copyMoveCommand, searchFile } from '@/api/file'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import PreviewPage from '@/componentsMain/Preview/index'
import { downloadCommand } from '@/api/file'
import { saveAs } from 'file-saver'
import { getSysDictByType } from '@/api/admin'
import {
  claimTask,
  findProcessUserTaskByPdId,
  getHighLightedProcessDiagram,
  findWorkflowBusinessByWbPageType,
  startGeneralReviewProcessInstance,
  getProcessResource
} from '@/api/activiti'
export default {
  name: '',
  directives: {
    clipboard,
    PreviewPage
  },
  components: {
    expandItem: {
      functional: true,
      props: {
        row: Object,
        render: Function,
        column: {
          type: Object,
          default: null
        }
      },
      render: (h, ctx) => {
        const params = {
          row: ctx.props.row
        }
        if (ctx.props.column) params.column = ctx.props.column
        return ctx.props.render(h, params)
      }
    }
  },
  props: {
    columns: {
      required: true,
      type: Array,
      default: () => {
        return []
      }
    },
    searchOtherData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    searchForm: {
      type: Array,
      default: () => {
        return []
      }
    },
    searchHandle: {
      type: Array,
      default: () => []
    },
    listApi: {
      type: String,
      default: ''
    },
    delApi: {
      type: String,
      default: ''
    },
    exportApi: {
      type: String,
      default: ''
    },
    exportName: {
      type: String,
      default: '表格'
    },
    isTreeData: {
      type: Boolean,
      default: false
    },
    pageType: {
      type: String,
      default: 'prjmgt'
      /*
        prjmgt： 科研项目；
        outsource： 外协项目；
        mechanism_research： 机理研究进展及成果；
        technology_research： 工艺研究进展及成果；
        tangible_results： 有形化成果库；
        new_progress： 国内外研究新进展；
        laws_regulations： 国家法律法规；
      */
    }
  },
  data() {
    return {
      /* 基础页面参数 */
      tableData: [],
      listLoading: false,
      tableHeight: '1329px',
      isList: true,
      curPath: {},
      breadcrumb: [],
      searchData: { businessId: '', targetId: '' },
      fileImg: { dir: require('@/assets/files/file-s-0.png'),
        zips: require('@/assets/files/file-s-2.png'),
        word: require('@/assets/files/file-s-3.png'),
        ppt: require('@/assets/files/file-s-4.png'),
        excel: require('@/assets/files/file-s-5.png'),
        txt: require('@/assets/files/file-s-6.png'),
        pdf: require('@/assets/files/file-s-7.png'),
        img: require('@/assets/files/file-s-9.png'),
        video: require('@/assets/files/file-s-10.png'),
        no: require('@/assets/files/file-s-11.png'),
        music: require('@/assets/files/file-s-1.png')
      },
      fileImgL: { dir: require('@/assets/files/file-b-0.png'),
        zips: require('@/assets/files/file-b-2.png'),
        word: require('@/assets/files/file-b-3.png'),
        ppt: require('@/assets/files/file-b-4.png'),
        excel: require('@/assets/files/file-b-5.png'),
        txt: require('@/assets/files/file-b-6.png'),
        pdf: require('@/assets/files/file-b-7.png'),
        img: require('@/assets/files/file-b-9.png'),
        video: require('@/assets/files/file-b-10.png'),
        no: require('@/assets/files/file-b-11.png'),
        music: require('@/assets/files/file-b-1.png')
      },
      styleObject: {
        top: '0',
        left: '0'
      },
      /* 选择参数 */
      selectionArr: [],
      checkAll: false,
      /* 上传附件及更新版本参数 */
      showUpload: false,
      fileList: [],
      isNewFile: true,
      uploadAction: '/api/file/sysfile/fileCommand',
      uploadHeader: { Authorization: 'Bearer ' + getToken() },
      uploadData: { fileBusiness: '', command: 'upload', fileStorageId: '', targetId: '', fileType: '', fileSource: 'other' },
      uploadRenewData: { fileBusiness: '', command: 'update', fileStorageId: '', targetId: '' },
      rulesUpload: { fileType: [{ required: true, message: '请选择附件类型！', trigger: 'change' }] },
      synTypeOptions: [],
      /* 审核参数 */
      selectedRow: {},
      checkType: '',
      tempCheck: {
        candidate: ''
      },
      rulesCheck: {
        checkType: [{ required: true, message: '请选择审核状态！', trigger: 'change' }],
        comment: [{ required: true, message: '请输入审核意见！', trigger: 'change' }]
      },
      /* 复制移动参数 */
      DirTree: [],
      dialogMoveStatus: '',
      dialogMoveOrCopyVisible: false,
      defaultProps: {
        children: 'list',
        label: 'fileDirName'
      },
      filterText: '',
      /* 历史版本参数 */
      historyList: [],
      activeNames: ['1', '2', '3', '4'],
      curVersion: '',
      /* 标签参数 */
      dynamicTags: ['标签一'],
      inputVisible: false,
      inputValue: '',
      /* 发起审核参数 */
      dialogFormVisible: false,
      priorityOptions: [],
      candidateOptions: [],
      workFlowOptions: [],
      temp: {
        id: undefined,
        candidate: '',
        rangeTime: '',
        priority: '',
        description: '',
        processDefinitionId: ''
      },
      textMap: {
        update: '发起审核',
        create: '新增'
      },
      rules: {
        processDefinitionId: [{ required: true, message: '请选择审核流程！', trigger: 'change' }],
        candidate: [{ required: true, message: '请选择审批人员！', trigger: 'change' }],
        rangeTime: [{ required: true, message: '请选择起止时间！', trigger: 'change' }],
        priority: [{ required: true, message: '请选择优先级！', trigger: 'change' }],
        description: [{ required: true, message: '请填写备注！', trigger: 'change' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      activeStep: 1,
      radio: '',
      /* 历史审核动态参数 */
      checkHistoryList: [],
      /* 跟踪 */
      trackDialogVisible: false,
      svgSrc: '',
      /* drag icon */
      isShowRight: true
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
    isAllUninitiated() {
      const isAll = this.selectionArr.some(info => {
        return !((info.wsStatus === null || info.wsStatus === 'terminated' || info.wsStatus === 'rejected' || info.wsStatus === 'delete') && info.createUsername === this.name && info.fileExtension !== null && (this.pageType === 'prjmgt' || this.pageType === 'new_processes' || this.pageType === 'summary'))
      })
      return !isAll
    },
    isAllSign() {
      const isAll = this.selectionArr.some(info => {
        return (info.wsStatus !== 'sign' || info.wsAssignee !== this.name || info.fileExtension === null)
      })
      return !isAll
    },
    isCheck() {
      const isAll = this.selectionArr.some(info => {
        return ((info.wsStatus === 'pending' || info.wsStatus === 'delegated') && info.wsAssignee === this.name) || ((info.wsStatus === 'delegate' || info.wsStatus === 'rollback') && info.taskDelegateAssignee === this.name)
      })
      return isAll
    },
    isDelegate() {
      const isAll = this.selectionArr.some(info => {
        return (info.wsStatus === 'pending' && info.wsAssignee === this.name)
      })
      return isAll
    },
    isTrack() {
      const isAll = this.selectionArr.some(info => {
        return (info.wsStatus === null || info.fileExtension === null || this.selectionArr.length > 1 || info.wsStatus === 'finished' || info.wsStatus === 'terminated')
      })
      return !isAll
    },
    isDel() {
      const isAll = this.selectionArr.some(info => {
        return (info.wsStatus === 'finished') || !(this.pageType === 'prjmgt' || this.pageType === 'new_processes' || this.pageType === 'summary')
      })
      return !isAll
    },
    isDownload() {
      const isAll = this.selectionArr.some(info => {
        return (info.wsStatus === 'finished' || ((info.wsStatus === 'delegate' || info.wsStatus === 'rollback') && (info.wsAssignee === this.name || info.wsOwner === this.name || info.wsDelegator === this.name)) || (info.wsStatus === 'pending' && info.wsAssignee === this.name) || info.createUsername === this.name) || (this.pageType === 'prjmgt' || this.pageType === 'new_processes' || this.pageType === 'summary')
      })
      return isAll
    },
    isRenew() {
      let isAll = false
      if (this.selectedRow.wsStatus === null || this.selectedRow.wsStatus === 'terminated' || this.selectedRow.wsStatus === 'rejected' || this.selectedRow.wsStatus === 'delete') {
        isAll = true
      }
      return isAll
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    pageType: {
      handler: function(val) {
        if (!(val === 'prjmgt' || val === 'outsource')) {
          this.uploadData.fileType = val
        }
        this.uploadData.fileSource = val
      },
      immediate: true
    }
  },
  created() {
    this.getList()
    this.getType()
    this.uploadData.fileBusiness = this.$route.query.id
    this.searchData.businessId = this.$route.query.id
    this.tableHeight = (document.body.clientHeight - 550) + 'px'
  },
  methods: {
    /* 页面基础功能——start */
    handleTableClass() {
      return 'tableHeader'
    },
    clipboardSuccess() {
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    parseTime(row, field) {
      const arr = field.split('.')
      if (arr.length === 1) {
        if (row[field]) {
          return moment(row[field]).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return ''
        }
      } else {
        if (row[arr[0]][arr[1]]) {
          return moment(row[arr[0]][arr[1]]).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return ''
        }
      }
    },
    /* 打开页面下一级目录或是文件— */
    handleOpenDirList(row) {
      if (row.fileExtension === null) {
        this.searchData.targetId = row.id
        this.getList()
        this.checkAll = false
      } else {
        this.selectedRow = row
        this.selectionArr = [row]
        this.handlePreviewOrCheck(row)
      }
    },
    handleOpenDir({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      if (row.fileExtension === null && $columnIndex === 1) {
        this.searchData.targetId = row.id
        this.getList()
      } else if ($columnIndex === 1) {
        this.selectedRow = row
        this.selectionArr = [row]
        this.handlePreviewOrCheck(row)
      }
    },
    fiiterFileImg(row, type) {
      switch (row.fileExtension) {
        case null: return this[type].dir
        case 'xlsx':
        case 'xls':
          return this[type].excel
        case 'pdf': return this[type].pdf
        case 'pptx': return this[type].ppt
        case 'doc':
        case 'docx':
          return this[type].word
        case 'txt': return this[type].txt
        case 'zip':
        case 'rar':
          return this[type].zips
        case 'jpg':
        case 'png': return this[type].img
        case 'mp4': return this[type].video
        default:
          return this[type].no
      }
    },
    /* 快捷列表 */
    handleCloseMoreList() {
      this.styleObject.display = 'none'
      this.styleObject.left = 0 + 'px'
      this.styleObject.top = 0 + 'px'
      this.styleObject.position = 'absolute'
    },
    handleMoreOptClick(item, event) {
      const x = event.pageX
      const y = event.pageY
      const clientHeight = document.body.clientHeight
      const cha = clientHeight - y
      if (cha > 223) {
        this.styleObject.left = (x) + 'px'
        this.styleObject.top = (y) + 'px'
      } else {
        this.styleObject.left = (x) + 'px'
        this.styleObject.top = (y - cha) + 'px'
      }
      this.styleObject.position = 'fixed'
      this.styleObject.display = 'block'
      if (this.isList) {
        this.$refs.xTree.clearCheckboxRow()
        this.$refs.xTree.setCheckboxRow(item, true)
      }
      this.selectedRow = item
      this.selectionArr = [item]
    },
    /* 面包屑回退功能 */
    goBackLink(info) {
      this.searchData.targetId = info.id
      this.getList()
    },
    /* checkbox change */
    handleSelectionChange({ records }) {
      this.selectionArr = records
    },
    clearSelection() {
      this.selectionArr = []
    },
    handleSelectionList(item) {
      const index = this.selectionArr.findIndex((n) => { return item.id === n.id })
      if (index < 0) {
        this.selectionArr.push(JSON.parse(JSON.stringify(item)))
      } else {
        this.selectionArr.splice(index, 1)
      }
      this.selectionArr.length === this.tableData.length ? this.checkAll = true : this.checkAll = false
    },
    handleCheckAllChange(val) {
      val ? this.selectionArr = JSON.parse(JSON.stringify(this.tableData)) : this.selectionArr = []
    },
    /* 排序 */
    sortDesByKey(ary, key) {
      return ary.sort((a, b) => {
        const x = a[key]
        const y = b[key]
        return ((x < y) ? 1 : (x > y) ? -1 : 0)
      })
    },
    /* 获取列表信息 */
    handleSearch() {
      this.listLoading = true
      if (this.searchData.fileName) {
        searchFile(this.searchData).then(response => {
          this.arrangeData(response)
          this.listLoading = false
        })
      } else {
        this.getList()
      }
    },
    getList() {
      this.listLoading = true
      this.searchData = Object.assign(this.searchData, this.searchOtherData)
      list['openDir'](this.searchData).then(response => {
        this.arrangeData(response)
        this.listLoading = false
      })
    },
    arrangeData(response) {
      if (response.data.list) {
        this.tableData = response.data.list
      } else {
        this.tableData = []
      }
      const info = response.data.currDir
      if (info) {
        this.curPath = info
        const arr = info.fileVirtualPath.split('\\')
        if ((arr.length - 1) > this.breadcrumb.length) {
          this.breadcrumb.push(info)
        } else if ((arr.length - 1) < this.breadcrumb.length) {
          this.breadcrumb = this.breadcrumb.slice(0, (arr.length - 1))
        }
      }
      this.uploadData.fileStorageId = this.curPath.fileFilestorageId
      this.uploadData.targetId = this.curPath.id
      this.clearSelection()
    },
    getType() {
      getSysDictByType('syn_type').then(response => {
        this.synTypeOptions = response.data
      })
      getSysDictByType('priority').then(response => {
        this.priorityOptions = response.data
      })
    },
    /* 文件功能— */
    /* 批量下载 */
    handleBatchDownLoad() {
      this.selectionArr.forEach((item) => {
        const formData = {
          id: item.id,
          command: 'file'
        }
        downloadCommand(formData).then(response => {
          saveAs(response, item.fileOriginalName)
        })
      })
    },
    handleDownLoad(item) {
      const formData = {
        id: item.id,
        command: 'file'
      }
      downloadCommand(formData).then(response => {
        saveAs(response, item.fileOriginalName)
      })
    },
    /* 复制移动功能 */
    findDirTree() {
      const businessId = this.$route.query.id
      findDirTree({ businessId: businessId }).then(response => {
        this.DirTree = [response.data]
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.fileName.indexOf(value) !== -1
    },
    handleBatchCopy() {
      this.dialogMoveOrCopyVisible = true
      this.dialogMoveStatus = '复制到'
      this.findDirTree()
    },
    handleBatchMove() {
      this.dialogMoveOrCopyVisible = true
      this.dialogMoveStatus = '移动到'
      this.findDirTree()
    },
    handleCopyOrMove(type) {
      const arr = []
      this.selectionArr.forEach((item) => {
        arr.push(item.id)
      })
      const formData = new FormData()
      formData.append('fileStorageId', this.curPath.fileFilestorageId)
      formData.append('targetId', this.$refs.tree.getCurrentKey())
      formData.append('fileBusiness', this.$route.query.id)
      formData.append('fileIds', arr)
      let isParent = false
      const parentKey = this.$refs.tree.getNode(this.$refs.tree.getCurrentKey()).data.filePidTree ? this.$refs.tree.getNode(this.$refs.tree.getCurrentKey()).data.filePidTree.split(',') : []
      arr.forEach((item) => {
        parentKey.forEach((n) => {
          if (n === item) {
            isParent = true
            return false
          }
        })
      })
      const index = arr.findIndex((n) => { return n === this.$refs.tree.getCurrentKey() })
      if (index > -1 || isParent) {
        this.handleWarning({ message: '不能移动或复制到自身及其子目录' })
        return false
      }
      if (this.curPath.id === this.$refs.tree.getCurrentKey()) {
        this.handleWarning({ message: '不能移动或复制到同级目录' })
        return false
      }
      if (type === 'Move') {
        formData.append('command', 'move')
        copyMoveCommand(formData).then(response => {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.dialogMoveOrCopyVisible = false
          this.getList()
        })
      } else {
        formData.append('command', 'copy')
        copyMoveCommand(formData).then(response => {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.dialogMoveOrCopyVisible = false
          this.getList()
        })
      }
    },
    /* 发起审核 */
    handleCandidate() {
      findProcessUserTaskByPdId(this.temp.processDefinitionId).then(response => {
        this.candidateOptions = response.data
        if (this.candidateOptions.assignee) {
          this.candidateOptions.assignee = [this.candidateOptions.assignee]
          this.temp.candidate = this.candidateOptions.assignee[0].username
          this.radio = 'assignee'
        } else {
          if (this.candidateOptions.candidateUsers) {
            this.radio = 'candidateUsers'
          } else {
            if (this.candidateOptions.candidateGroups) {
              this.radio = 'candidateGroups'
            } else {
              this.radio = ''
            }
          }
        }
      })
    },
    changeStep(type, field) {
      if (type === 'next') {
        this.$refs['dataForm'].validateField(field, (emailError) => {
          if (!emailError) {
            this.activeStep++
          }
        })
      } else {
        this.activeStep--
      }
    },
    changeRadio(value) {
      if (value === 'assignee') {
        if (this.dialogFormVisible) {
          this.temp.candidate = this.candidateOptions.assignee[0].username
        } else {
          this.tempCheck.candidate = this.candidateOptions.assignee[0].username
        }
      } else {
        this.temp.candidate = ''
        this.tempCheck.candidate = ''
      }
    },
    handleStart(row) {
      this.dialogFormVisible = true
      this.activeStep = 1
      findWorkflowBusinessByWbPageType('file_detail').then(response => {
        this.workFlowOptions = response.data
        if (this.workFlowOptions.length === 1) {
          this.temp.processDefinitionId = this.workFlowOptions[0].wbProcDefId
          this.handleCandidate()
          this.activeStep = 2
          getProcessResource(this.workFlowOptions[0].workflowDeploymentId).then(response => {
            this.svgSrc = response
          })
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    // 发起审核
    startData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.startCheck()
        }
      })
    },
    async startCheck() {
      for (let i = 0; i < this.selectionArr.length; i++) {
        const item = this.selectionArr[i]
        await startGeneralReviewProcessInstance({
          candidate: this.temp.candidate,
          priority: this.temp.priority,
          startTime: this.temp.rangeTime ? this.temp.rangeTime[0] : null,
          endTime: this.temp.rangeTime ? this.temp.rangeTime[1] : null,
          description: this.temp.description,
          processDefinitionId: this.temp.processDefinitionId,
          customForm: [],
          businessId: item.fileId
        }).then(() => {
          this.$notify({
            title: '成功',
            message: '发起审核成功',
            type: 'success',
            duration: 2000
          })
        })
      }
      this.dialogFormVisible = false
      this.getList()
    },
    /* 签收 */
    async handleAssign() {
      for (let i = 0; i < this.selectionArr.length; i++) {
        const item = this.selectionArr[i]
        await claimTask(item.wsTaskId).then(response => {
          this.$notify({
            title: '成功',
            message: '签收任务成功',
            type: 'success',
            duration: 2000
          })
        })
      }
      this.getList()
    },
    /* 跟踪 */
    handleTrack() {
      getHighLightedProcessDiagram(this.selectionArr[0].wsProcInstId).then(response => {
        this.svgSrc = response.data
        this.trackDialogVisible = true
      }).catch(() => {
        this.svgSrc = ''
      })
    },
    /* 预览&审核 */
    handlePreviewOrCheck(row) {
      this.$router.push({ name: 'fileDetail', query: row })
    },
    /* 更新版本&重命名 */
    handleRenew(row) {
      this.fileList = []
      this.showUpload = true
      this.isNewFile = false
      this.uploadRenewData.fileBusiness = this.$route.query.id
      this.uploadRenewData.fileStorageId = this.curPath.fileFilestorageId
      this.uploadRenewData.targetId = row.id
    },
    handleEdit(row) {
      let name = row.fileOriginalName
      if (row.fileExtension !== null) {
        const arr = row.fileOriginalName.split('.')
        arr.splice(arr.length - 1, 1)
        name = arr.join('')
      }
      this.$prompt('请输入文件名', '重命名文件名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '文件名不能为空',
        inputValue: name
      }).then(({ value }) => {
        const formData = new FormData()
        formData.append('fileStorageId', this.curPath.fileFilestorageId)
        formData.append('command', 'rename')
        formData.append('targetId', row.id)
        formData.append('fileBusiness', this.$route.query.id)
        if (row.fileExtension === null) {
          formData.append('dirName', value)
          dirCommand(formData).then(response => {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        } else {
          formData.append('fileName', value)
          fileCommand(formData).then(response => {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.selectedRow.fileOriginalName = value
          })
        }
      }).catch(() => {
      })
    },
    /* 删除功能 */
    handleBatchDel() {
      let arr = []
      this.selectionArr.forEach((item) => {
        arr.push(item.id)
      })
      arr = arr.join(',')
      this.handleDelete(arr)
    },
    handleDelete(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '删除中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        list[this.delApi](ids).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          loading.close()
          this.getList()
        }).catch(() => {
          loading.close()
        })
      })
    },
    handleWarning(response) {
      this.$notify({
        title: '警告',
        message: response.message,
        type: 'warning',
        duration: 2000
      })
    },
    /* 创建文件夹 */
    handleCreateDir() {
      this.$prompt('请输入文件名', '创建文件名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '文件名不能为空'
      }).then(({ value }) => {
        const formData = new FormData()
        formData.append('dirName', value)
        formData.append('fileStorageId', this.curPath.fileFilestorageId)
        formData.append('command', 'mkdir')
        formData.append('targetId', this.curPath.id)
        formData.append('fileBusiness', this.$route.query.id)
        dirCommand(formData).then(response => {
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
      })
    },
    /* 上传 */
    handleUpload() {
      this.fileList = []
      this.showUpload = true
      this.isNewFile = true
    },
    handleSuccess(response) {
      if (response.status === 200) {
        this.showUpload = false
        this.getList()
      } else {
        this.fileList = []
        this.handleWarning(response)
      }
    },
    handleSuccessRenew(response) {
      if (response.status === 200) {
        this.showUpload = false
        this.getList()
      } else {
        this.fileList = []
        this.handleWarning(response)
      }
    },
    handleBeforeUpload() {
      let validate = true
      this.$refs['dataFormUpload'].validate((valid) => {
        if (valid) {
          validate = true
        } else {
          this.$notify({
            title: '警告',
            message: '请选择附件类型',
            type: 'warning',
            duration: 2000
          })
          this.fileList = []
          validate = false
        }
      })
      return validate
    },
    handleExceed() {
      this.handleWarning('当前限制选择 1 个文件, 您已超出限制')
    },
    /* 标签功能 */
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped lang="scss">
.basic-page{
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  height: calc(100vh - 380px);
  overflow: auto;
  width: 100%;
}
.ces-search {
  display: flex;
  align-items: center;
  justify-content:space-between;
}
.ces-search .el-form-item{
  margin-bottom: 0 !important;
}
.block{
  margin-top: 40px;
  text-align: center;
}
.el-icon-copy-document{
  /*color: #0984ff;*/
  color: #333333;
  cursor: pointer;
  margin-left: 10px;
}
.co-icon-zg-folder-opened-fill, .co-icon-folder_opened{
  color: #f5d672;
}

[class^=co-icon-]{
  margin-right: 10px;
  font-size: 24px;
}

.el-icon-document{
  margin-right: 10px;
  font-size: 20px;
}
.drag-btn{
  user-select: none;
}
.card-list{
  display: flex;
  list-style: none;
  padding: 0;
  li{
    position: relative;
    padding-top: 18px;
    margin: 4px 0 0 6px;
    text-align: center;
    color: #666666;
    font-size: 12px;
    width: 120px;
    height: 157px;
    cursor: pointer;
    border-radius: 5px;
    .card-content{
      margin: 9px auto 0;
      background-repeat: no-repeat;
      overflow: hidden;
    }
    .card-txt{
      display: block;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      margin: 6px 5px 5px;
    }
  }
  .normal{
    .el-icon-success{
     visibility: hidden;
    }
    &:hover{
      background: rgba(0, 191, 244, 0.1);
      .el-icon-success{
        visibility: visible;
        position: absolute;
        top:10px;
        left: 10px;
        font-size: 20px;
        color: #bde6ea;
      }
    }

  }
  .active{
    background: rgba(0, 191, 244, 0.1);
    .el-icon-success{
      visibility: visible;
      position: absolute;
      top:10px;
      left: 10px;
      font-size: 20px;
      color: #00bff4;
    }
  }
}
.moreList{
  display: none;
  list-style: none;
  border: 1px solid #dde0e4;
  border-radius: 5px;
  box-shadow: 0 0 8px #ccc;
  min-height: 23px;
  padding: 2px 0;
  position: absolute;
  background-color: #FFF;
  z-index: 100;
  li{
    cursor: default;
    width: 130px;
    height: 23px;
    line-height: 23px;
    white-space: nowrap;
    position: relative;
    z-index: 1;
    box-sizing: border-box;
    padding: 0 27px 0 20px;
    margin: 0;
    font-size: 13px!important;
    color: #5b667b!important;
    &:hover {
      background: rgba(0, 191, 244, 0.1);
    }
  }
}
.el-divider--horizontal{
  margin: 5px 0 !important;
}
.check-box{
  display: flex;
  .file-content{
    flex: 1;
    height: calc(100vh - 60px);
    overflow: hidden;
    position: relative;
    .collapse{
      position: absolute;
      z-index: 1000;
      font-size: 60px;
      right: 0;
      padding: 130px 20px;
      top: 50%;
      transform: translate(0, -50%);
      color: transparent;
      &:hover{
        color: #FFFFFF;
        background: rgba(0,0,0,0.5);
        border-radius: 5px 0 0 5px;
      }
    }
  }
  .detail{
    width: 800px;
    margin-left: 20px
  }
  .hideDetail{
    width: 0;
    display: none;
  }
}
.title-wrapper{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 50px;
  text-align: right;
}
.versionWrapper{
  display: flex;
  justify-content: space-between;
  cursor: pointer;
  color: #8c8c8c;
  .el-icon-aim{
    color: #1890ff;
    margin-right: 10px;
    font-size: 16px;
  }
  .createName{
    font-size: 14px;
  }
  .fileName{
    font-size: 12px;
  }
  &:hover{
    color: #000000;
  }
}
.versionWrapper.active{
  color: #000000;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.el-icon-collection-tag{
  margin-right: 10px;
  font-size: 24px;
}
</style>
